package com.zhentao.common.service.impl;

import com.zhentao.common.config.MinioConfig;
import com.zhentao.common.config.MinioConfigProperties;
import com.zhentao.common.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
@EnableConfigurationProperties(MinioConfigProperties.class)
@Import(MinioConfig.class)
public class FileStorageServiceImpl implements FileStorageService {
    @Autowired
    private MinioConfigProperties minioConfigProperties;
    @Autowired
    private MinioClient minioClient;
    @SneakyThrows
    @Override
    public String uploadHtml(String fileName, InputStream inputStream) {
        PutObjectArgs build = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fileName)
                .contentType("text/html")
                .stream(inputStream, inputStream.available(), -1)
                .build();
        minioClient.putObject(build);
        String path = minioClient.getObjectUrl(build.bucket(), build.object());
        return path;
    }

    @SneakyThrows
    @Override
    public String uploadImage(String fileName, InputStream inputStream) {
        PutObjectArgs build = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fileName)
                .contentType("image/jpg")
                .stream(inputStream, inputStream.available(), -1)
                .build();
        minioClient.putObject(build);
        String path = minioClient.getObjectUrl(build.bucket(), build.object());
        return path;
    }
}
